<template>
  <div>
    <HeaderDe></HeaderDe>
    <div>
      <h3 style="text-align: center">多熠电商-每日库存结算（达能）</h3>
      <LwBordor></LwBordor>
    </div>
    <div>
      <el-date-picker
          v-model="selectedDate"
          type="date"
          placeholder="选择日期"
          @change="dateChange"
      >
      </el-date-picker>
      <el-button style="margin-left: 10px;" size="big" type="success" @click.prevent="exportInventoryNew()"
                 :loading="loadingExport">导出
      </el-button>
      <el-button type="primary" style="margin-left: 10px" @click="importData">导入库存</el-button>

      <el-table :data="tableData" stripe style="margin-top: 20px;" class="m-table"
                :header-cell-style="{textAlign:'center',background: '#07a023' ,color:'#1d1d1d'}"
                :cell-style="{textAlign:'center'}" v-loading="loading" border>
        <el-table-column prop="outerId" label="商品编码"></el-table-column>
        <el-table-column prop="barcode" label="规格条码"></el-table-column>
        <el-table-column prop="goodsName" label="商品名称"></el-table-column>
        <el-table-column prop="skuName" label="规格名称"></el-table-column>
        <el-table-column prop="normalQuantity" label="良品库存"></el-table-column>
        <el-table-column prop="substandardQuantity" label="残次品"></el-table-column>
        <el-table-column prop="brokenQuantity" label="残品"></el-table-column>
        <el-table-column prop="boxBrokenQuantity" label="盒损"></el-table-column>
        <el-table-column prop="quantity" label="总库存"></el-table-column>
      </el-table>

      <el-pagination
          style="margin-top: 20px; text-align: right;"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 200]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      >
      </el-pagination>

      <el-dialog title="导入库存" :visible.sync="dialogVisible">
        <div class="import-container">
          <el-date-picker
              v-model="dialogDate"
              type="date"
              placeholder="选择日期"
              style="margin-bottom: 20px;"
          ></el-date-picker>
          <el-upload
              :action="url+uploadUrl"
              :data="{'inventoryDate':dialogDate}"
              ref="upload"
              :limit="1"
              :multiple="false"
              accept=".xls,.xlsx"
              :auto-upload="false"
              :on-success="uploadSuccess"
          >
            <el-button slot="trigger" size="big" type="primary" style="margin-left: 20px">选取文件</el-button>
            <el-button style="margin-left: 10px;" size="big" type="success" @click="submitImport">导入数据</el-button>
            <div slot="tip" class="el-upload__tip" style="text-align: center">只能上传xlsx/xls文件</div>
          </el-upload>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import LwBordor from "@/views/lw/LwBordor.vue";
import HeaderDe from "@/components/HeaderDe.vue";

export default {
  components: {HeaderDe, LwBordor},
  data() {
    return {
      url: this.$http_java.defaults.baseURL,
      uploadUrl: '/upload/uploadInventoryNew',
      selectedDate: new Date(),
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      loadingExport: false,
      dialogVisible: false,
      dialogDate: new Date()
    };
  },
  methods: {
    dateChange() {
      this.currentPage = 1;
      this.fetchData();
    },
    fetchData() {
      const _this = this
      if (_this.selectedDate === null) {
        return
      }
      _this.$http_java.post("/page/inventoryNewList", {
        "inventoryDate": _this.selectedDate,
        "page": _this.currentPage,
        "pageSize": _this.pageSize,
      }).then(res => {
        console.log(res.data)
        if (res.data.code === 0) {
          console.log("res", res)
          _this.tableData = res.data?.data?.records
          console.log("tableData", _this.tableData)
          _this.total = res.data?.data?.total
          // _this.dialogVisible = true;
          // _this.$alert('操作成功', '提示', {
          //     confirmButtonText: '确定',
          //     callback: action => {
          //         // _this.$router.push("/blogs")
          //     }
          // });
        } else {
          _this.$alert('操作失败:' + JSON.stringify(res.data), '提示', {
            confirmButtonText: '确定',
            callback: action => {
              // _this.$router.push("/blogs")
            }
          });
        }
      })
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchData();
    },
    importData() {
      const _this = this
      _this.dialogVisible = true
      // Logic for importing data
      console.log('Import data');
    },
    uploadSuccess(res, file, fileList) {
      console.log(res)
      console.log(file)
      const _this = this
      if (res.code === 0) {
        _this.$alert("【" + file.name + '】操作成功，共录入' + res.data + "条数据!", '提示', {
          confirmButtonText: '确定',
          callback: action => {
            // _this.$router.push("/blogs")
            _this.dialogVisible = false
            _this.dateChange()
            this.$refs.upload.clearFiles()
          }
        });
        this.refreshOuterId();
      } else {
        // console.log(1111)
        _this.$alert("【" + file.name + '】操作失败：' + ((Object.keys(res.data).length === 0) ? res.message : res.data), '提示', {
          confirmButtonText: '确定',
          callback: action => {
            // _this.$router.push("/blogs")
            _this.dialogVisible = false
            this.$refs.upload.clearFiles()
          }
        });
      }
    },
    submitImport() {
      this.$refs.upload.submit();
    },
    exportInventoryNew() {
      // ② 全局+字
      // const loading = this.$loading({
      //     lock: true,
      //     text: '正在导出',
      //     spinner: "el-icon-loading",
      //     background: 'raba(0, 0, 0, 0.7)'
      // });
      // ③ 按钮动画
      this.loadingExport = true;
      this.$message({
        type: "warning",
        message: "数据正在导出，请耐心等待"
      });

      //!important 如果要在下面的函数中用结构体this 必须先把this赋予变量 结构体中调用_this!!!!
      const _this = this

      this.$http_java({
        method: 'get',
        url: "/page/exportInventoryNew",
        params: {"inventoryDate": _this.selectedDate,},
        responseType: 'blob'
      }).then(function (response) {
        // ② 全局+字
        // loading.close();

        // ① 全局+转圈
        // let loadingInstance = Loading.service({target: document.body});
        // this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
        //     loadingInstance.close();
        // });
        console.log(response)
        var fileURL = window.URL.createObjectURL(new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}));
        var fileLink = document.createElement('a');

        fileLink.href = fileURL;
        console.log("111", response.headers)
        /*
       todo
        中文名乱码后端找了一下午找不到问题
        从前端找找啊啊啊啊！
        前端这里可以打印出来所有的header啊啊啊啊啊啊啊
        在这里用decodeURI一下不就可以把后端转的urlcode转为中文了吗.....
        反正前端肯定是认识urlcode的！！！！
         */
        const tomorrow = new Date(_this.selectedDate);
        tomorrow.setDate(tomorrow.getDate() + 1);
        fileLink.setAttribute('download', decodeURI("库存导出结果" + tomorrow.toISOString().split('T')[0] + ".xlsx"));

        document.body.appendChild(fileLink);

        fileLink.click();
        // ③ 按钮动画
        _this.loadingExport = false;
        _this.$message({
          type: "success",
          duration: 1000,
          message: "操作成功"
        });
      })
    },
  },
  mounted() {
    this.fetchData();
  },
};
</script>

<style scoped>
.import-container {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>